package user

import (
	. "bysy-gin/handler"
	"bysy-gin/libs/auth"
	"bysy-gin/libs/token"
	"bysy-gin/model"
	"github.com/gin-gonic/gin"
)

func Register(c *gin.Context) {
	var u model.UserModel
	if err := c.ShouldBindJSON(&u); err != nil {
		SendResponse(c, 1001, "数据绑定失败!", nil)
		return
	}
	//加密密码
	if err := u.Encryt(); err != nil {
		SendResponse(c, 1005, "数据加密失败！", nil)
		return
	}

	if err := u.Create(); err != nil {
		SendResponse(c, 1002, "写入数据失败!", nil)
		return
	}
	SendResponse(c, 0, "success!", u)
}

// 接收登录信息的结构体
type UserLogin struct {
	UserName string `json:"username"  binding:"required"`
	Password string `json:"password" binding:"required"`
}

func Login(c *gin.Context) {
	//绑定数据
	var userlogin UserLogin
	if err := c.ShouldBindJSON(&userlogin); err != nil {
		//SendResponse(c, 1001, "绑定数据失败！", nil)
		SendRsp(c, err, nil)
		return
	}

	//根据用户名查询
	u, err := model.GetUser(userlogin.UserName)
	if err != nil {
		SendResponse(c, 1005, "没有这个用户，登录失败！", nil)
		return
	}
	//比较密码是否正确
	if err := auth.Compare(u.Password, userlogin.Password); err != nil {
		SendResponse(c, 1005, "密码错误，登录失败!", nil)
		return
	}
	//生成token
	if t, err := token.Sign(token.Context{ID: u.Id, UserName: u.Username}, ""); err != nil {
		SendResponse(c, 1008, "token生成失败!", nil)
		return
	} else {
		SendResponse(c, 0, "登录成功,返回token!", t)
		return
	}
}
